from django.shortcuts import render

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from regist.models import UserInfo


# Create your views here.


def test(request):
    '''test'''
    return HttpResponse('ok')


def index(req):
    """首页"""


    return render(req, 'loginTemplates/index.html')


def loginPage(req):
    """登陆展示页"""
    # 读取cookie 显示账户号
    if 'userName' in req.COOKIES:
        userName = req.COOKIES["userName"]
    else:
        userName = ''
    return render(req, 'loginTemplates/login.html', {"userName": userName})


@csrf_exempt  # 添加csrftoken的免检装饰器
def loginAction(req):
    """登陆_ajax"""

    # 获取用户提交的用户名密码
    queryDic = req.POST
    userName = queryDic['userName']
    pwd = queryDic['password']

    # 去mysql匹配
    try:
        user = UserInfo.objects.get(userName=userName)
        pass
    except BaseException:
        print('-----ERROR-----')
        return JsonResponse({"success": '0', "msg": '用户名或密码不正确'})
        pass
    else:
        # 返回匹配结果
        if user.userName == userName:
            print(user.password)
            print(pwd)
            if user.password == pwd:
                # 登陆成功,设置cookie , 保存登陆成功的用户名
                response = JsonResponse({"success": '1', "msg": '登陆成功'})
                response.set_cookie("userName", userName, max_age=12 * 24 * 3600)
                return response
                pass
            else:
                return JsonResponse({"success": '0', "msg": '用户名或密码不正确'})
        else:
            return JsonResponse({"success": '0', "msg": '用户名或密码不正确'})


def showUser(req):
    """查看所有注册的用户"""
    return render(req, 'loginTemplates/allUser.html')


@csrf_exempt
def showUserAction(req):
    """查看所有注册的用户_ajax"""
    # 查询数据库
    user = UserInfo.objects.all()
    dictArr = []

    for item in user:
        dict = {}
        dict['userName'] = item.userName
        dict['passwd'] = item.password
        dictArr.append(dict)
        print(dict)
    # 返回给ajax

    return JsonResponse({"data": dictArr})
